package com.boruan.shengtangfeng.core.utils;

import java.util.ArrayList;
import java.util.List;

import com.boruan.shengtangfeng.core.dao.ILogDao;
import com.boruan.shengtangfeng.core.entity.Log;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WriteLogThread extends Thread{
	private ILogDao logDao;
	public WriteLogThread(){
	}
	public WriteLogThread(ILogDao logDao){
		this.logDao=logDao;
	}
	public void run() {
		try {
			while(Global.LOG_THREAD_RUN){
				int count = saveLog();
				//如果没有需要处理的日志，线程休息，避免死循环
				if (count<=0) {
					try {
//						logger.debug("登录日志队列为空，休眠"+Global.LOG_THREAD_SLEEP_TIME);
						Thread.sleep(Global.LOG_THREAD_SLEEP_TIME);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 保存搜索日志
	 * @return 本次处理记录条数
	 */
	private int saveLog(){
		int count=0;
		try {
			if (Global.logQueue!=null && !Global.logQueue.isEmpty()) {
				List<Log> logList = new ArrayList<Log>();
				Log sysLog=null;
				while ((sysLog=Global.logQueue.poll()) != null) {
					logList.add(sysLog);
					count++;
					if (count>=Global.SAVE_COUNT) {
						break;
					}
				}
				//插入数据库
				logDao.insertBatch(logList);
				log.info("日志写入数据库条数:{}",count);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}
}
